//
//  HCWLocationManager.m
//  LuckSteer
//
//  Created by BOOU on 15/11/26.
//  Copyright © 2015年 BOOU. All rights reserved.
//

#import "HCWLocationManager.h"
#import "WGS84TOGCJ02.h"

#define IS_iOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO)

@interface HCWLocationManager() <CLLocationManagerDelegate>
@end

@implementation HCWLocationManager

+ (instancetype)sharedManager
{
    static HCWLocationManager *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HCWLocationManager alloc] init];
    });
    
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if ( self )
    {
        self.minSpeed = 3;
        self.minFilter = 1000;
        self.minInteval = 5;

        if ([CLLocationManager locationServicesEnabled] ) {  // 判断是否开启了定位服务
            self.delegate = self;
            self.distanceFilter  = self.minFilter;
            self.desiredAccuracy = kCLLocationAccuracyBest;
            if (IS_iOS8) {
                [self requestWhenInUseAuthorization];
            }
            
        } else{
            // 未开启定位服务
        }
        
    }
    return self;
}

- (void)startUpdatingLocation:(LocationFinishBlock)finishBlock
                   errorBlock:(LocationErrorBlock)errorBlock
{
    self.locationFinishBlock = finishBlock;
    self.locationErrorBlock = errorBlock;
    
    if (![CLLocationManager locationServicesEnabled]) {
        if (self.locationErrorBlock) {
            self.locationErrorBlock(0, nil);
        }
    }
    
    [self startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = locations[0];
    [manager stopUpdatingLocation];
    
  //  NSLog(@"%@",location);

    if (self.locationFinishBlock) {
        self.locationFinishBlock(location);
    }
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (self.locationErrorBlock) {
        self.locationErrorBlock(1, error);
    }
}

/**
 *  规则: 如果速度小于minSpeed m/s 则把触发范围设定为50m
 *  否则将触发范围设定为minSpeed*minInteval
 *  此时若速度变化超过10% 则更新当前的触发范围(这里限制是因为不能不停的设置distanceFilter,
 *  否则uploadLocation会不停被触发)
 */
- (void)adjustDistanceFilter:(CLLocation*)location
{
    if ( location.speed < self.minSpeed )
    {
        if ( fabs(self.distanceFilter-self.minFilter) > 0.1f )
        {
            self.distanceFilter = self.minFilter;
        }
    }
    else
    {
        CGFloat lastSpeed = self.distanceFilter/self.minInteval;
        
        if ( (fabs(lastSpeed-location.speed)/lastSpeed > 0.1f) || (lastSpeed < 0) )
        {
            CGFloat newSpeed  = (int)(location.speed+0.5f);
            CGFloat newFilter = newSpeed*self.minInteval;
            
            self.distanceFilter = newFilter;
        }
    }
}

@end
